package com.gulimall.common.exception;

import com.gulimall.common.utils.ResponseCode;
import com.gulimall.common.utils.ServiceResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.TypeMismatchException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingPathVariableException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.async.AsyncRequestTimeoutException;
import org.springframework.web.multipart.support.MissingServletRequestPartException;

import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;

@Slf4j
public class ExceptionProcessor {

    @ExceptionHandler({HttpRequestMethodNotSupportedException.class,
            HttpMediaTypeNotSupportedException.class,
            MissingPathVariableException.class,
            MissingServletRequestParameterException.class,
            TypeMismatchException.class,
            HttpMessageNotReadableException.class,
            HttpMessageNotWritableException.class,
            HttpMediaTypeNotAcceptableException.class,
            ServletRequestBindingException.class,
            MissingServletRequestPartException.class,
            AsyncRequestTimeoutException.class})
    public ResponseEntity<ServiceResponse<Void>> handleServletException(Exception e) {
        log.error(e.getMessage(), e);
        if (e instanceof HttpRequestMethodNotSupportedException) {
            return getResponseEntity(HttpStatus.BAD_REQUEST,
                    ResponseCode.REQUEST_NOT_SUPPORTED_ERROR.getCode(), ResponseCode.REQUEST_NOT_SUPPORTED_ERROR.getMessage());
        } else if (e instanceof HttpMediaTypeNotSupportedException) {
            return getResponseEntity(HttpStatus.UNSUPPORTED_MEDIA_TYPE,
                    ResponseCode.MEDIA_TYPE_NOT_SUPPORTED_ERROR.getCode(), ResponseCode.MEDIA_TYPE_NOT_SUPPORTED_ERROR.getMessage());
        } else if (e instanceof MissingPathVariableException) {
            return getResponseEntity(HttpStatus.BAD_REQUEST,
                    ResponseCode.MISSING_PATH_VARIABLE_ERROR.getCode(), ResponseCode.MISSING_PATH_VARIABLE_ERROR.getMessage());
        } else if (e instanceof MissingServletRequestParameterException) {
            return getResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR,
                    ResponseCode.MISSING_REQUEST_PARAM_ERROR.getCode(), ResponseCode.MISSING_REQUEST_PARAM_ERROR.getMessage());
        } else if (e instanceof TypeMismatchException) {
            return getResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR,
                    ResponseCode.TYPE_MISMATCH_ERROR.getCode(), ResponseCode.TYPE_MISMATCH_ERROR.getMessage());
        } else if (e instanceof HttpMessageNotReadableException) {
            return getResponseEntity(HttpStatus.BAD_REQUEST,
                    ResponseCode.HTTP_MESSAGE_NOT_READABLE_ERROR.getCode(), ResponseCode.HTTP_MESSAGE_NOT_READABLE_ERROR.getMessage());
        } else if (e instanceof HttpMessageNotWritableException) {
            return getResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR,
                    ResponseCode.HTTP_MESSAGE_NOT_WRITABLE_ERROR.getCode(), ResponseCode.HTTP_MESSAGE_NOT_WRITABLE_ERROR.getMessage());
        } else if (e instanceof HttpMediaTypeNotAcceptableException) {
            return getResponseEntity(HttpStatus.NOT_ACCEPTABLE,
                    ResponseCode.MEDIA_TYPE_NOT_ACCEPTABLE_ERROR.getCode(), ResponseCode.MEDIA_TYPE_NOT_ACCEPTABLE_ERROR.getMessage());
        } else if (e instanceof ServletRequestBindingException) {
            return getResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR,
                    ResponseCode.REQUEST_BINDING_ERROR.getCode(), ResponseCode.REQUEST_BINDING_ERROR.getMessage());
        } else if (e instanceof MissingServletRequestPartException) {
            return getResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR,
                    ResponseCode.MISSING_REQUEST_PART_ERROR.getCode(), ResponseCode.MISSING_REQUEST_PART_ERROR.getMessage());
        } else if (e instanceof AsyncRequestTimeoutException) {
            return getResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR,
                    ResponseCode.ASYNC_REQUEST_TIMEOUT_ERROR.getCode(), ResponseCode.ASYNC_REQUEST_TIMEOUT_ERROR.getMessage());
        } else {
            return getResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR,
                    ResponseCode.SERVER_ERROR.getCode(), ResponseCode.SERVER_ERROR.getMessage());
        }
    }

    /**
     * <p>处理数据绑定异常</p>
     *
     * @param e 数据绑定异常
     * @return 服务响应
     */
    @ExceptionHandler(BindException.class)
    public ResponseEntity<ServiceResponse<Void>> handleBindingException(BindException e) {
        log.error(e.getMessage(), e);
        return new ResponseEntity<>(getBindingResult(e.getBindingResult()), HttpStatus.INTERNAL_SERVER_ERROR);
    }

    /**
     * <p>处理参数无效异常</p>
     *
     * @param e 参数无效异常
     * @return 服务响应
     */
    @ExceptionHandler({MethodArgumentNotValidException.class})
    public ResponseEntity<ServiceResponse<Void>> handleArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error(e.getMessage(), e);
        return new ResponseEntity<>(getBindingResult(e.getBindingResult()), HttpStatus.OK);
    }

    /**
     * <p>处理违反约束异常</p>
     *
     * @param exception 违反约束异常
     * @return 服务响应
     */
    @ExceptionHandler({ConstraintViolationException.class})
    public ResponseEntity<ServiceResponse<Void>> handleConstraintViolationException(ConstraintViolationException exception) {
        log.error(exception.getMessage(), exception);
        ServiceResponse<Void> response = new ServiceResponse<>(ResponseCode.PARAMETER_VALID_ERROR.getCode(),
                ResponseCode.PARAMETER_VALID_ERROR.getMessage());
        response.setMessage(response.getMessage() + exception.toString());
        return new ResponseEntity<>(response, HttpStatus.OK);
    }

    /**
     * <p>处理校验异常</p>
     *
     * @param e 校验异常
     * @return 服务响应
     */
    @ExceptionHandler({ValidationException.class})
    public ResponseEntity<ServiceResponse<Void>> handleValidationException(
            ValidationException e) {
        log.error(e.getMessage(), e);
        ServiceResponse<Void> response = new ServiceResponse<>(ResponseCode.PARAMETER_VALID_ERROR.getCode(),
                ResponseCode.PARAMETER_VALID_ERROR.getMessage());
        response.setMessage(response.getMessage() + e.getMessage());
        return new ResponseEntity<>(response, HttpStatus.OK);
    }

    /**
     * <p>处理业务异常</p>
     *
     * @param e 业务异常
     * @return 服务响应
     */
    @ExceptionHandler(value = BusinessException.class)
    public ResponseEntity<ServiceResponse<?>> handleBusinessException(BusinessException e) {
        log.error(e.getMessage(), e);
        ServiceResponse<?> response = new ServiceResponse<>(e.getCode(), e.getMessage());
        return new ResponseEntity<>(response, HttpStatus.OK);
    }

    /**
     * <p>未知异常处理</p>
     *
     * @param e 异常
     * @return 服务响应
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseEntity<ServiceResponse<Void>> handleException(
            Exception e) {
        ResponseEntity<ServiceResponse<Void>> responseEntity =
                getResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR,
                        ResponseCode.SERVER_ERROR.getCode(), ResponseCode.SERVER_ERROR.getMessage());
        log.error(e.getMessage(), e);
        return responseEntity;
    }

    /**
     * <p>构造异常返回实体</p>
     *
     * @param httpCode http响应码
     * @param code     服务返回码
     * @param message  服务返回信息
     * @return ResponseEntity 服务响应
     */
    private ResponseEntity<ServiceResponse<Void>> getResponseEntity(HttpStatus httpCode, int code, String message) {
        ServiceResponse<Void> serviceResponse = new ServiceResponse<>(code, message);
        return new ResponseEntity<>(serviceResponse, httpCode);
    }

    /**
     * <p>包装绑定异常结果</p>
     *
     * @param bindingResult 绑定结果
     * @return 服务响应
     */
    private ServiceResponse<Void> getBindingResult(BindingResult bindingResult) {
        StringBuilder message = new StringBuilder();
        for (ObjectError error : bindingResult.getAllErrors()) {
            message.append(", ");
            if (error instanceof FieldError) {
                message.append(((FieldError) error).getField()).append(": ");
            }
            message.append(error.getDefaultMessage() == null ? "" : error.getDefaultMessage());
        }

        ServiceResponse<Void> response = new ServiceResponse<>(ResponseCode.PARAMETER_VALID_ERROR.getCode(),
                ResponseCode.PARAMETER_VALID_ERROR.getMessage());
        if (message.length() > 2) {
            response.setMessage(response.getMessage() + message.substring(2));
        }
        return response;
    }
}
